package com.uenpay.im.ui.old.activity.group;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qyx.android.entity.GroupTalkEntity;
import com.qyx.android.message.type.MsgContentType;
import com.qyx.android.message.type.PacketType;
import com.qyx.android.protocol.BaseContentModel;
import com.qyx.android.protocol.SessionModel;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.chat.ChatActivity;
import com.uenpay.im.ui.old.activity.red.RedHandler;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.entities.chatbean.MsgRedModel;
import com.uenpay.im.weight.RoundImageView;
import com.uenpay.util.app.base.BaseActivity;

import java.util.ArrayList;

/**
 * 我的群列表
 *
 * @author SL
 * @copyRight http://www.qiyunxin.com
 */
public class MyGroupsActivity extends BaseActivity {

    public ArrayList<GroupTalkEntity> groups;
    private ListView my_groups_list;
    private MyGroupsadapter adapter;
    private View loading;
    private TextView no_group_tv;
    private GroupMangerHandler groupMangerHandler = new GroupMangerHandler();
    private BaseContentModel forwardMsg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        super.onCreate(savedInstanceState);
        IMApplication.getInstance().addActivity(this);
        Bundle bu = getIntent().getExtras();
        if (bu != null && bu.getParcelable("forwardMsg") != null) {
            forwardMsg = bu.getParcelable("forwardMsg");
        }
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_list_layout;
    }

    @Override
    public void initView(View view) {
        initView();
        initListener();
        loading.setVisibility(View.VISIBLE);
        getData();
    }

    protected void initView() {
        ((TextView) findViewById(R.id.title_textview)).setText(getResources()
                .getString(R.string.my_groups));
        ((TextView) findViewById(R.id.title_right_tv)).setText(getResources()
                .getString(R.string.create_group));
        findViewById(R.id.title_right_layout).setVisibility(View.VISIBLE);
        my_groups_list = (ListView) findViewById(R.id.listview);
        no_group_tv = (TextView) findViewById(R.id.no_data_tv);
        no_group_tv.setText(R.string.not_join_any_group);
        loading = findViewById(R.id.loading);
    }

    protected void initListener() {
        //返回键点击
        findViewById(R.id.back_layout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                finish();
            }
        });
        findViewById(R.id.title_right_layout).setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        Intent intent = new Intent(MyGroupsActivity.this,
                                AddGroupMemberActivity.class);
                        startActivity(intent);
                    }
                });
        my_groups_list.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                GroupTalkEntity gt = (GroupTalkEntity) arg0.getAdapter()
                        .getItem(arg2);
                if (gt == null) {
                    return;
                }
                getGroupDetailInfo(gt.group_id + "");
                if (forwardMsg != null
                        && forwardMsg.getType() == MsgContentType.RED) {
                    sendRed(gt.group_id + "", gt.group_name, gt.org_type_id);
                } else {
                    startTalk(gt.group_id + "", gt.group_name, gt.org_type_id);
                }
            }
        });
    }

    private RedHandler mRedHandler = new RedHandler();

    /***
     * 红包转发
     *
     * @param chatid
     */
    private void sendRed(final String chatid, final String chat_name,
                         final int operationType) {
        loading.setVisibility(View.VISIBLE);
        String red_packet_id = "";
        MsgRedModel msgRedModel = (MsgRedModel) forwardMsg;
        if (msgRedModel != null) {
            red_packet_id = msgRedModel.getPacketsid();
        }
        mRedHandler.sendRed(red_packet_id, chatid, PacketType.GROUP,
                new RedHandler.ISendRedResult() {

                    @Override
                    public void onSendResult(int status, String reason) {
                        loading.setVisibility(View.GONE);
                        if (status == HttpInvokeResultCode.RESULT_OK)
                            startTalk(chatid, chat_name, operationType);
                        else if (!TextUtils.isEmpty(reason)) {
                            IMApplication.showToast(reason);
                        }
                    }
                });
    }

    /**
     * 开始会话
     *
     * @param chatId
     * @param chat_name
     * @param operationType
     */
    private void startTalk(String chatId, String chat_name, int operationType) {
        Bundle bu = new Bundle();
        SessionModel sessionModel = new SessionModel();
        sessionModel.setSessionId(Long.valueOf(chatId));
        sessionModel.setSessionType(PacketType.GROUP);
        sessionModel.setOperationType(operationType);
        bu.putParcelable("session", sessionModel);
        bu.putString("stranger_name", chat_name);
        Intent intent = new Intent();
        intent.putExtras(bu);
        if (forwardMsg != null) {
            setResult(RESULT_OK, intent);
        } else {
            intent.setClass(MyGroupsActivity.this, ChatActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            IMApplication.IS_REFRESH_TOP_MSG = true;
        }
        finish();
    }

    private void getData() {
        groupMangerHandler.getMyGroups(new GroupMangerHandler.IGetMyGroupsListener() {

            @Override
            public void onGetMyGroupsResult(int status, String msg,
                                            ArrayList<GroupTalkEntity> groups) {
                myHandler.sendEmptyMessage(0);
                if (status == HttpInvokeResultCode.RESULT_OK && groups != null) {
                    if (groups.size() < 1) {
                        myHandler.sendEmptyMessage(1);
                    }
                    if (adapter == null) {
                        adapter = new MyGroupsadapter(MyGroupsActivity.this,
                                groups);
                        my_groups_list.setAdapter(adapter);
                    } else {
                        adapter.setData(groups);
                    }

                } else {
                    my_groups_list.setVisibility(View.GONE);
                    no_group_tv.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    class MyGroupsadapter extends BaseAdapter {
        LayoutInflater inflater;
        private ArrayList<GroupTalkEntity> groups;

        public MyGroupsadapter(Context mContext,
                               ArrayList<GroupTalkEntity> _groups) {
            inflater = LayoutInflater.from(mContext);
            groups = _groups;
        }

        public void addData(ArrayList<GroupTalkEntity> _groups) {
            groups.addAll(_groups);
            notifyDataSetChanged();
        }

        public void setData(ArrayList<GroupTalkEntity> _groups) {
            groups = _groups;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return groups == null ? 0 : groups.size();
        }

        @Override
        public Object getItem(int arg0) {
            return groups == null ? 0 : groups.get(arg0);
        }

        @Override
        public long getItemId(int arg0) {
            return groups == null ? 0 : arg0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final MyGroupsViewHolder holder;
            GroupTalkEntity gt = groups.get(position);
            if (convertView == null) {
                holder = new MyGroupsViewHolder();
                convertView = inflater.inflate(R.layout.my_groups_list_item,
                        parent, false);
                holder.iv = (RoundImageView) convertView
                        .findViewById(R.id.my_groups_avatar);
                holder.name = (TextView) convertView
                        .findViewById(R.id.my_groups_name);
                holder.funds_group_tv = (TextView) convertView
                        .findViewById(R.id.funds_group_tv);
                convertView.setTag(holder);
            } else {
                holder = (MyGroupsViewHolder) convertView.getTag();
            }

            holder.name.setText(gt.group_name);
            if (gt.org_type_id == 3) {
                holder.funds_group_tv.setVisibility(View.VISIBLE);
            } else {
                holder.funds_group_tv.setVisibility(View.GONE);
            }
            holder.iv.SetUrl(APIConfiguration.getAvatarUrlNormal(gt.group_id
                    + "", PacketType.GROUP));
            return convertView;
        }

        class MyGroupsViewHolder {
            private RoundImageView iv;
            private TextView name, funds_group_tv;
        }

    }

    public Handler myHandler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 0) {
                if (loading != null) {
                    loading.setVisibility(View.GONE);
                }
            } else if (msg.what == 1) {
                if (no_group_tv != null) {
                    no_group_tv.setVisibility(View.VISIBLE);
                }
                if (my_groups_list != null) {
                    my_groups_list.setVisibility(View.GONE);
                }
            }
            return false;
        }
    });

    @Override
    protected void onDestroy() {
        IMApplication.getInstance().removeActivity(this);
        super.onDestroy();
    }

    /**
     * 获取群聊详情
     *
     * @param chatId
     */
    private void getGroupDetailInfo(String chatId) {
        groupMangerHandler.getGroupDetail(chatId, null);
    }

}
